<%-
  object_name = unique_object_name_for("update_context_#{@context.id}")
-%>
var <%=object_name%> = {
  <% unless @saved -%>
    animate: function() {
      TracksPages.show_edit_errors(<%=object_name%>.html_for_error_messages());
    },
    html_for_error_messages: function() {
      return "<%= js_error_messages_for(@context) %>";
    }
  <% else -%>
    animate: function() {
      TracksPages.page_inform('<%= t('contexts.save_status_message') %>');
      <% if @state_changed -%>
        <%=object_name%>.remove_and_re_add_context();
        <%=object_name%>.update_container_states();
      <% else -%>
        <%=object_name%>.replace_context_form_with_updated_context();
      <% end -%>
      TracksForm.set_context_name_and_default_context_name("<%= escape_javascript(@context.name)%>");
    },
    remove_and_re_add_context: function() {
      $('#<%=dom_id(@context, 'container')%>').slideUp(500, function() {
        $('#<%=dom_id(@context, 'container')%>').remove();
        $('#list-contexts-<%=@new_state%>').append(<%=object_name%>.html_for_context_listing());
      });
    },
    replace_context_form_with_updated_context: function() {
      $('#<%=dom_id(@context, 'container')%>').fadeOut(250, function() {
      <%
        # first add the updated context after the old one, then remove old one
        # using html() does not work, because it will replace the _content_ of
        # the container instead of the container itself, i.e. you will get
        # a container within a container which will break drag-and-drop sorting
      -%>
        $('#<%=dom_id(@context, 'container')%>').after(<%=object_name%>.html_for_context_listing());
        $('#<%=dom_id(@context, 'container')%>').remove();
        $('#<%=dom_id(@context, 'container')%>').fadeIn(500);
      });
    },
    update_container_states: function() {
      ContextListPage.update_all_states_count(<%=@active_contexts.count%>, <%=@hidden_contexts.count%>, <%=@closed_contexts.count%>);
    },
    html_for_context_listing: function() {
      return "<%= js_render('context_listing', {}, @context)%>";
    }
  <% end -%>
}

<%=object_name%>.animate();
